package com.ruoyi.procurementmanagement.service.impl;

import com.ruoyi.procurementmanagement.domain.ErpGoodsLabel;
import com.ruoyi.procurementmanagement.domain.ErpGoodsLabelRelation;
import com.ruoyi.procurementmanagement.mapper.ErpGoodsLabelMapper;
import com.ruoyi.procurementmanagement.mapper.ErpGoodsLabelRelationMapper;
import com.ruoyi.procurementmanagement.service.IErpGoodsLabelRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class ErpGoodsLabelRelationServiceImpl implements IErpGoodsLabelRelationService {

    @Autowired
    private ErpGoodsLabelRelationMapper relationMapper;

    @Autowired
    private ErpGoodsLabelMapper labelMapper;

    @Override
    @Transactional
    public void updateGoodsLabelRelations(Long goodsId, List<Long> labelIds) {
        // 确保goodsId不为null
        if (goodsId == null) {
            throw new IllegalArgumentException("goodsId不能为null");
        }

        // 先删除旧的关系
        relationMapper.deleteByGoodsId(goodsId);

        // 再添加新的关系
        if (labelIds != null && !labelIds.isEmpty()) {
            for (Long labelId : labelIds) {
                if (labelId != null) {
                    relationMapper.insertErpGoodsLabelRelation(goodsId, labelId);
                }
            }
        }
    }

    @Override
    public List<ErpGoodsLabel> getGoodsLabels(Long goodsId) {
        if (goodsId == null) {
            return Collections.emptyList();
        }
        return labelMapper.selectLabelsByGoodsId(goodsId);
    }
}
